package com.dc.system.service.impl;

import com.dc.base.exception.BusinessException;
import com.dc.common.constants.ConstantsCommon;
import com.dc.common.model.BaseModel;
import com.dc.system.mapper.SysOrganMapper;
import com.dc.system.mapper.SysRoleMapper;
import com.dc.system.model.SysOrgan;
import com.dc.system.model.SysRole;
import com.dc.system.model.SysRoleOrgan;
import com.dc.system.model.SysUser;
import com.dc.system.service.SysRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: SysRoleServiceImpl
 * @Author: ChenXueLi
 * @Date: 2018-05-06 19:08
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysOrganMapper sysOrganMapper;

    /**
     * 添加一个角色
     * @param sysRole
     * @param baseModel
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public BaseModel addSysRole(SysRole sysRole, BaseModel baseModel, HttpServletRequest request) throws Exception {
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }
        if(sysRole.getName() == null || "".equals(sysRole.getName())) {

        }
        String organId = request.getParameter("organ_id");
        if(organId != null && !"".equals(organId)) {
            // 查询单位是否存在
            SysOrgan sysOrgan = sysOrganMapper.getSysOrganById(Integer.valueOf(organId));
            if (sysOrgan == null) {
                throw new BusinessException(-102, "获取单位失败");
            }
        }
        // 设置默认参数
        sysRole.setCreate_time(new Date());
        sysRole.setCreate_user_name(sysUser.getAccount());
        sysRole.setCreate_user_id(sysUser.getUser_id());
        sysRole.setUpdate_time(new Date());
        sysRole.setUpdate_user_name(sysUser.getAccount());
        sysRole.setUpdate_user_id(sysUser.getUser_id());
        sysRole.setIs_deleted(1);
        sysRole.setVersion(0);

        int effectRows = sysRoleMapper.addSysRole(sysRole);
        if(effectRows != 1) {
            throw new BusinessException(-103, "系统错误，添加角色失败");
        }
        baseModel.setCode(0);
        sysRole = sysRoleMapper.getSysRoleById(sysRole.getRole_id());
        baseModel.setData(sysRole);

        // 添加绑定单位
        if(organId != null && !"".equals(organId)) {
            SysRoleOrgan sysRoleOrgan = new SysRoleOrgan();
            sysRoleOrgan.setFk_role_id(sysRole.getRole_id());
            sysRoleOrgan.setFk_organ_id(Integer.valueOf(organId));
            effectRows = sysRoleMapper.addSysRoleOrgan(sysRoleOrgan);
            if(effectRows != 1) {
                baseModel.setMessage("添加角色成功，但是绑定单位失败");
            }
        }
        baseModel.setMessage("添加角色成功");
        return baseModel;
    }

    /**
     * 根据角色id删除一个角色
     * @param sysRole
     * @param baseModel
     * @param request
     * @return
     */
    @Override
    public BaseModel deleteSysRoleById(SysRole sysRole, BaseModel baseModel, HttpServletRequest request) throws Exception {
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }
        sysRole = sysRoleMapper.getSysRoleById(sysRole.getRole_id());
        if(sysRole == null) {
            throw new BusinessException(-102, "获取角色失败");
        }
        sysRole.setUpdate_time(new Date());
        sysRole.setUpdate_user_name(sysUser.getAccount());
        sysRole.setUpdate_user_id(sysUser.getUser_id());
        sysRole.setIs_deleted(0);
        int effectRows = sysRoleMapper.deleteSysRoleById(sysRole);
        if(effectRows != 1) {
            throw new BusinessException(-103, "系统错误，删除角色失败");
        }
        // 删除绑定单位
        sysRoleMapper.deleteSysRoleOrgan(sysRole.getRole_id(), null);

        baseModel.setMessage("删除角色成功");
        baseModel.setCode(0);
        baseModel.setData(sysRole);
        return baseModel;
    }

    /**
     * 根据角色id查询角色
     * @param sysRole
     * @param baseModel
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public BaseModel getSysRoleById(SysRole sysRole, BaseModel baseModel, HttpServletRequest request) throws Exception {
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }
        sysRole = sysRoleMapper.getSysRoleById(sysRole.getRole_id());
        if(sysRole == null) {
            throw new BusinessException(-102, "获取角色失败");
        }
        baseModel.setMessage("查询成功");
        baseModel.setCode(0);
        baseModel.setData(sysRole);
        return baseModel;
    }

    /**
     * 修改一个角色的信息
     * @param sysRole
     * @param baseModel
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public BaseModel updateSysRoleById(SysRole sysRole, BaseModel baseModel, HttpServletRequest request) throws Exception {
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }
        SysRole originalSysRole = sysRoleMapper.getSysRoleById(sysRole.getRole_id());
        if(originalSysRole == null) {
            throw new BusinessException(-102, "获取角色失败");
        }
        if(sysRole.getName() == null || "".equals(sysRole.getName())) {
            throw new BusinessException(-103, "角色名称不能为空");
        }
        String organId = request.getParameter("organ_id");
        if(organId != null && !"".equals(organId)) {
            // 查询单位是否存在
            SysOrgan sysOrgan = sysOrganMapper.getSysOrganById(Integer.valueOf(organId));
            if (sysOrgan == null) {
                throw new BusinessException(-102, "获取单位失败");
            }
        }
        // 修改绑定单位
        if(organId != null && !"".equals(organId)) {
            List<SysRole> sysRoles = sysRoleMapper.getSysRolesByOrganId(Integer.valueOf(organId));
            Boolean flag = null;
            if(sysRoles != null && sysRoles.size() > 0) {
                flag = false;
                // 查看是否有当前的角色id
                for(SysRole temp : sysRoles) {
                    if(temp.getRole_id() == sysRole.getRole_id()) {
                        // 存在了。不需要修改
                        flag = true;
                        break;
                    }
                }
            }
            SysRoleOrgan sysRoleOrgan = new SysRoleOrgan();
            sysRoleOrgan.setFk_role_id(sysRole.getRole_id());
            sysRoleOrgan.setFk_organ_id(Integer.valueOf(organId));
            if(flag == null) {
                // 直接添加
                sysRoleMapper.addSysRoleOrgan(sysRoleOrgan);
            }else if(!flag) {
                // 删除再添加
                sysRoleMapper.deleteSysRoleOrgan(sysRole.getRole_id(),null);
                sysRoleMapper.addSysRoleOrgan(sysRoleOrgan);
            }
        }

        sysRole.setUpdate_time(new Date());
        sysRole.setUpdate_user_name(sysUser.getAccount());
        sysRole.setUpdate_user_id(sysUser.getUser_id());
        sysRole.setVersion(originalSysRole.getVersion());

        int effectRows = sysRoleMapper.updateSysRoleById(sysRole);
        if(effectRows != 1) {
            throw new BusinessException(-104, "系统错误，修改角色失败");
        }
        baseModel.setMessage("修改角色成功");
        baseModel.setCode(0);
        sysRole = sysRoleMapper.getSysRoleById(sysRole.getRole_id());
        baseModel.setData(sysRole);
        return baseModel;
    }

    /**
     * 分页查询角色
     * @param pageInfo
     * @param sysRole
     * @param baseModel
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public BaseModel getSysRoles(PageInfo<?> pageInfo, SysRole sysRole, BaseModel baseModel, HttpServletRequest request) throws Exception {
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }
        Map<String, Object> params = new HashMap<>();
        if(sysRole.getName() != null && !"".equals(sysRole.getName())) {
            params.put("name", sysRole.getName());
        }
        if(sysRole.getCreate_user_id() != 0 && !"".equals(sysRole.getCreate_user_id())) {
            params.put("create_user_id", sysRole.getCreate_user_id());
        }
        if(sysRole.getCreate_user_name() != null && !"".equals(sysRole.getCreate_user_name())) {
            params.put("create_user_name", sysRole.getCreate_user_name());
        }
        if(sysRole.getUpdate_user_id() != 0 && !"".equals(sysRole.getUpdate_user_id())) {
            params.put("update_user_id", sysRole.getUpdate_user_id());
        }
        if(sysRole.getUpdate_user_name() != null && !"".equals(sysRole.getUpdate_user_name())) {
            params.put("update_user_name", sysRole.getUpdate_user_name());
        }
        // 创建时间开始
        String create_time_start = request.getParameter("create_time_start");
        if(create_time_start != null && !"".equals(create_time_start)) {
            params.put("create_time_start", create_time_start);
        }
        // 创建时间结束
        String create_time_end = request.getParameter("create_time_end");
        if(create_time_end != null && !"".equals(create_time_end)) {
            params.put("create_time_end", create_time_end);
        }
        // 修改时间开始
        String update_time_start = request.getParameter("update_time_start");
        if(update_time_start != null && !"".equals(update_time_start)) {
            params.put("update_time_start", update_time_start);
        }
        // 修改时间结束
        String update_time_end = request.getParameter("update_time_end");
        if(update_time_end != null && !"".equals(update_time_end)) {
            params.put("update_time_end", update_time_end);
        }
        String organId = request.getParameter("organ_id");
        // 添加单位信息
        if(organId != null && !"".equals(organId)) {
            params.put("organId", Integer.valueOf(organId));
        }
        // 判断是否需要分页查询（默认为分页查询）
        String getByPage = request.getParameter("getByPage");
        if(getByPage != null && !"".equals(getByPage)) {
            // 只要有值就不是分页查询
            List<SysRole> sysRoles = sysRoleMapper.getSysRoles(params);
            baseModel.setData(sysRoles);
            baseModel.setMessage("查询成功");
        }else {
            int pageNum = pageInfo.getPageNum() <= 0 ? 0 : pageInfo.getPageNum();
            int pageSize = pageInfo.getPageSize() <= 0 ? 10 : pageInfo.getPageSize();
            // 分页插件,但是PageHelper必须在查询语句前，最好写在service实现层
            PageHelper.startPage(pageNum, pageSize);
            List<SysRole> sysRoles = sysRoleMapper.getSysRoles(params);
            // 通过pageHelper插件pageInfo封装，更加方便
            PageInfo<SysRole> resultSysDept = new PageInfo<SysRole>(sysRoles);
            baseModel.setData(resultSysDept);
            baseModel.setMessage("查询成功");
        }
        return baseModel;
    }

}
